package com.demon.framework.util.authection;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demon.framework.common.exception.BizException;
import com.demon.framework.common.model.constants.HeaderConstants;
import com.demon.framework.common.model.enums.LoginTypeEnum;
import com.demon.framework.common.retcode.BaseRetCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * @author fangyi
 * @description
 * @date 2019/2/9
 */

public class JWTUtil {
    /**
     * 过期时间-14天，单位：毫秒
     */
    public static final long EXPIRE_TIME = 14 * 24 * 60 * 60 * 1000L;

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String phone, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("phone", phone)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return 手机号
     */
    public static String getPhone() {
        return getPhone(getToken());
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return 手机号
     */
    public static String getPhone(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("phone").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得用户id
     *
     * @return 用户id
     */
    public static Long getUserId() {
        return getUserId(getToken());
    }

    /**
     * 获得用户id
     *
     * @return 用户id
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("uid").asLong();
        } catch (JWTDecodeException e) {
            throw new BizException(BaseRetCode.TOKEN_EXPIRED);
        }
    }

    /**
     * 获取token
     */
    public static String getToken() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return requestAttributes.getRequest().getHeader(HeaderConstants.TOKEN);
        } catch (Exception e) {
            throw new BizException(BaseRetCode.TOKEN_EXPIRED);
        }
    }

    /**
     * 生成签名
     *
     * @param uid           用户ID
     * @param phone         用户名,手机号
     * @param secret        用户的密码
     * @param loginTypeEnum 登录类型
     * @return 加密的token
     */
    public static String sign(Long uid, String phone, String secret, LoginTypeEnum loginTypeEnum) {
        try {
            Date expDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带phone信息
            return JWT.create()
                    .withClaim("phone", phone)
                    .withClaim("uid", uid)
                    // 登录类型:1:手机验证码,2-支付宝,3-微信,4-iphone
                    .withClaim("loginType", loginTypeEnum.getType())
                    .withExpiresAt(expDate)
                    .sign(algorithm);
        } catch (JWTCreationException e) {
            throw new BizException(BaseRetCode.TOKEN_EXPIRED);
        }
    }

}
